package com.chaoyong.higo.activity;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.chaoyong.higo.R;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.bean.GetgoodsAllBean;
import com.chaoyong.higo.bean.PersonInfoBean;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.DialogHelper;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.ImageUtils;
import com.chaoyong.higo.utils.JLog;
import com.chaoyong.higo.utils.PrefUtils;
import com.chaoyong.higo.utils.StringUtils;
import com.chaoyong.higo.utils.UploadPictureUtil;
import com.chaoyong.higo.utils.V;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.RoundImageView;
import com.chaoyong.higo.view.SelectPhotoesPopWin;
import com.chaoyong.higo.view.SelectSexPopWin;
import com.chaoyong.higo.view.SelectPhotoesPopWin.OnPhotoSelectedListener;
import com.chaoyong.higo.view.SelectSexPopWin.OnSexSelectedListener;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tw.pickerview.DatePickerPopWin;
import com.tw.pickerview.DatePickerPopWin.OnDatePickedListener;
import com.tw.wheel.popwin.AreaPickPopWin;
import com.tw.wheel.popwin.AreaPickPopWin.OnAreaPickedListener;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 个人资料
 * 
 * @author zk
 *
 */
public class PersonalDataActivity extends BaseActivity {

	private static final String ClassName = PersonalDataActivity.class.getName();
	private LinearLayout base_left_iv;// 左侧返回按钮
	private TextView base_title_tv;// 标题
	private TextView base_right_tv;// 标题右侧文字

	/** 头像所在布局 */
	private RelativeLayout data_image_lay;
	/** 头像 */
	private RoundImageView data_head_img;
	/** 昵称 */
	private TextView data_nick_name;
	/** 性别 */
	private TextView data_person_sex;
	/** 生日 */
	private TextView data_person_birth;
	/** 现住地 */
	private TextView data_now_home;
	/** 家乡 */
	private TextView data_hometown;
	/** 签名 */
	private TextView data_qian_ming;
	private String uid;

	@Override
	public int layoutResID() {
		return R.layout.activity_personal_data;
	}

	@Override
	public void findView() {
		findTitleIds();

		data_image_lay = V.f(this, R.id.data_image_lay);
		data_head_img = V.f(this, R.id.data_head_img);
		data_nick_name = V.f(this, R.id.data_nick_name);
		data_person_sex = V.f(this, R.id.data_person_sex);
		data_now_home = V.f(this, R.id.data_now_home);
		data_hometown = V.f(this, R.id.data_hometown);
		data_qian_ming = V.f(this, R.id.data_qian_ming);
		data_person_birth = V.f(this, R.id.data_person_birth);
	}

	private void findTitleIds() {
		base_left_iv = V.f(this, R.id.base_left_iv);
		base_title_tv = V.f(this, R.id.base_title_tv);
		base_right_tv = V.f(this, R.id.baseduobao_right_tv);

		base_title_tv.setText("设置");
		base_right_tv.setVisibility(View.GONE);
	}

	@Override
	public void init() {
		base_left_iv.setOnClickListener(this);
		data_image_lay.setOnClickListener(this);
		data_nick_name.setOnClickListener(this);
		data_person_sex.setOnClickListener(this);
		data_now_home.setOnClickListener(this);
		data_hometown.setOnClickListener(this);
		data_qian_ming.setOnClickListener(this);
		data_person_birth.setOnClickListener(this);

		uid = PrefUtils.getString(PersonalDataActivity.this, "userId", "1");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.base_left_iv:// title左侧返回
			this.finish();
			break;
		case R.id.data_image_lay:// 头像
			// showToast("头像");
			selectPicture();
			break;
		case R.id.data_nick_name:// 昵称
			// showToast("昵称");
			startActivity(new Intent(this, PersonalDataNicknameActivity.class));
			break;
		case R.id.data_person_sex:// 性别
			// showToast("性别");
			selectSex();
			break;
		case R.id.data_person_birth:// 生日
			 selectBirthday();
			break;
		case R.id.data_now_home:// 现住地
			// showToast("现住地");
			selectArea(data_now_home, "user_place");
			break;
		case R.id.data_hometown:// 家乡
			// showToast("家乡");
			selectArea(data_hometown, "home_place");
			break;
		case R.id.data_qian_ming:// 签名
			// showToast("签名");
			startActivity(new Intent(this, PersonalDataAutographActivity.class));
			break;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		String uid = PrefUtils.getString(PersonalDataActivity.this, "userId", "1");
		// httpQueryPersonInfo(uid);
		// httpQueryPersonInfo("1");
	}

	/**
	 * 查询个人信息
	 * 
	 * @param uid
	 */
	private void httpQueryPersonInfo(String uid) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();

			jsonObject.putOpt("model", "MemberInfo");
			jsonObject.putOpt("function", "index");
			jsonObject.putOpt("info", info);

			info.putOpt("uid", uid);

			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMember, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				Gson gson = new Gson();
				PersonInfoBean bean = gson.fromJson(arg0.result, PersonInfoBean.class);
				String status = bean.getStatus();
				if (status.equals("1")) {
					PersonInfoBean.DataEntity entities = bean.getData();
					if (entities != null) {
						setDatas(entities);
					}
				}
			}
		});
	}

	/**
	 * 设置个人数据
	 * 
	 * @param entities
	 */
	private void setDatas(PersonInfoBean.DataEntity entities) {
		// 头像
		String uid_portrait = (String) entities.getUid_portrait();
		// 昵称
		String dear_name = entities.getDear_name();
		// 性别
		String sex = entities.getSex();
		List<String> birth = entities.getBirthday();
		// 签名
		String signature = entities.getSignature();
		// 先住地
		List<String> user_place = entities.getUser_place();
		String user_pla = user_place.get(0);
		// 家乡
		List<String> home_place = entities.getHome_place();
		String home_pla = home_place.get(0);
		int size = birth.size();
		// if (birth.get(0) != null) {
		if (size == 1) {
			data_person_birth.setText("未设置");
		} else {
			data_person_birth.setText(birth.get(0) + "-" + birth.get(1) + "-" + birth.get(2));
		}

		if (!EmptyUtil.isEmpty(uid_portrait)) {
			ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uid_portrait, data_head_img);
			// bitmapUtils.display(data_head_img, Values.BASE_IMAGE_URL +
			// uid_portrait);
		} else {
			// bitmapUtils.display(data_head_img, "drawable://"+
			// R.drawable.head_image);
			ImageLoader.getInstance().displayImage("drawable://" + R.drawable.head_image, data_head_img);
		}

		if (!EmptyUtil.isEmpty(dear_name)) {
			data_nick_name.setText(dear_name + "");
		} else {
			data_nick_name.setText("");
		}

		if (sex.equals("1")) {
			data_person_sex.setText("男");
		} else if (sex.equals("2")) {
			data_person_sex.setText("女");
		}

		if (!EmptyUtil.isEmpty(signature)) {
			data_qian_ming.setText(signature + "");
		} else {
			data_qian_ming.setText("");
		}

		if (!EmptyUtil.isEmpty(user_place)) {
			data_now_home.setText(user_pla + "");
		}
		if (!EmptyUtil.isEmpty(home_place)) {
			data_hometown.setText(home_pla + "");
		}

	}

	/**
	 * 修改生日
	 */
	private void selectBirthday() {
		DatePickerPopWin datePickerPopWin = new DatePickerPopWin.Builder(this, new OnDatePickedListener() {

			@Override
			public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
				data_person_birth.setText(dateDesc);
				String str = year + "-" + month + "-" + day;
				httpNotifyBirth(uid, str);
			}
		}).textCancel("取消").textConfirm("确定").colorCancel(0x7f090026).colorConfirm(0x7f090026).maxYear(2500)
				.minYear(1900).build();
		datePickerPopWin.showPopWin(this);
	}

	/**
	 * 选择地区
	 * 
	 * @param tv
	 */
	private void selectArea(final TextView tv, final String place) {
		AreaPickPopWin areaPickPopWin = new AreaPickPopWin.Builder(this, new OnAreaPickedListener() {

			@Override
			public void onAreaPickCompleted(String province, String city, String district, String areaDesc) {
				tv.setText(areaDesc);
				httpNotifyUserPlace(uid, place, areaDesc);
			}
		}).textCancel("取消").textConfirm("确定").colorCancel(0x7f090026).colorConfirm(0x7f090026).build();
		areaPickPopWin.showPopWin(PersonalDataActivity.this);
	}

	/**
	 * 选择相册或相机
	 * 
	 */
	private void selectPicture() {
		// DialogHelper.getSelectDialog(this,
		// getResources().getStringArray(R.array.choice_pic),
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// showToast("" + which);
		// UploadPictureUtil.goToSelectPicture(PersonalDataActivity.this,
		// which);
		// }
		// }).setPositiveButton(null, null).show();
		SelectPhotoesPopWin photoesPopWin = new SelectPhotoesPopWin.Builder(this, new OnPhotoSelectedListener() {

			@Override
			public void onPhotoSelected(int which) {
				UploadPictureUtil.goToSelectPicture(PersonalDataActivity.this, which);
			}
		}).build();
		photoesPopWin.showPopWin(this);
	}

	/** 选择性别 */
	private void selectSex() {
		SelectSexPopWin popWin = new SelectSexPopWin.Builder(this, new OnSexSelectedListener() {

			@Override
			public void onSexSelected(String sex) {
				data_person_sex.setText(sex);
				if (sex.equals("男")) {
					httpNotifySex(uid, "1");
				} else if (sex.equals("女")) {
					httpNotifySex(uid, "2");
				}
			}
		}).build();
		popWin.showPopWin(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK)
			return;
		switch (requestCode) {
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
			// 拍照后裁剪
			UploadPictureUtil.startActionCrop(this, UploadPictureUtil.origUri);
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
			// 选图后裁剪
			UploadPictureUtil.startActionCrop(this, data.getData());
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
			uploadNewPhoto(data_head_img);
			break;
		}
	}

	private void uploadNewPhoto(ImageView imageView) {
		Bitmap bitmap = null;
		File file = null;
		if (!StringUtils.isEmpty(UploadPictureUtil.protraitPath) && UploadPictureUtil.protraitFile.exists()) {
			UploadPictureUtil.protraitBitmap = ImageUtils.loadImgThumbnail(UploadPictureUtil.protraitPath, 400, 250);
			bitmap = UploadPictureUtil.protraitBitmap;
			file = UploadPictureUtil.protraitFile;
		} else {
			showToast("图像不存在，上传失败");
		}
		if (bitmap != null) {
			imageView.setImageBitmap(bitmap);
			// TODO 网络请求
			upload(file);
		}
	}

	private void upload(File file) {
		// TODO Auto-generated method stub
		/*
		 * JSONObject json = new JSONObject(); try { json.put("uid", uid); }
		 * catch (JSONException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		RequestParams params = new RequestParams();
		params.addBodyParameter("uid", uid);
		params.addBodyParameter("img", file, "image/*");
		/*
		 * try { params.setBodyEntity(new StringEntity(json.toString(),
		 * "UTF-8")); } catch (UnsupportedEncodingException e) { // TODO
		 * Auto-generated catch block e.printStackTrace(); }
		 */

		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, OApi.appport_appUpload, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				try {
					JSONObject jso = new JSONObject(result);
					if (jso.getInt("status") == 1) {
						upload2(jso.getString("data"));
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	private void upload2(String url) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("uid", uid);
			json.put("img", url);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, OApi.appport_saveUserImg, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				try {
					JSONObject json = new JSONObject(result);
					if (json.getInt("status") == 1) {
						String uid = PrefUtils.getString(PersonalDataActivity.this, "userId", "1");
						httpQueryPersonInfo(uid);
						showToast("上传成功！");
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 修改生日
	 * 
	 * @param uid
	 * @param birthday
	 */
	private void httpNotifyBirth(String uid, String birthday) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();
			// 这俩货是默认值
			jsonObject.putOpt("model", "MemberInfo");
			jsonObject.putOpt("function", "setAppMemberInfo");

			info.put("birthday", birthday);
			info.put("uid", uid);

			jsonObject.putOpt("info", info);

			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMemberInfo, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
				showToast("修改失败");
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				showToast("修改完成");
			}
		});
	}

	/**
	 * 修改性别
	 * 
	 * @param uid
	 * @param which
	 *            "1"男，“2”女，“3”保密
	 */
	private void httpNotifySex(String uid, String which) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();
			jsonObject.putOpt("username", "");
			jsonObject.putOpt("info", info);
			// 这俩货是默认值
			jsonObject.putOpt("model", "MemberInfo");
			jsonObject.putOpt("function", "setAppMemberInfo");
			info.put("sex", which);
			info.put("uid", uid);
			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMemberInfo, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
				showToast("修改失败");
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				showToast("修改完成");
			}
		});
	}

	/**
	 * 修改用户地址
	 * 
	 * @param uid
	 *            用户id
	 * @param place
	 *            用户地址（“home_place”：家乡所在地；"user_place":现住地）
	 * @param content
	 */
	private void httpNotifyUserPlace(String uid, String place, String content) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();
			jsonObject.putOpt("username", "");
			jsonObject.putOpt("info", info);
			// 这俩货是默认值
			jsonObject.putOpt("model", "MemberInfo");
			jsonObject.putOpt("function", "setAppMemberInfo");
			info.put(place, content);
			info.put("uid", uid);
			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMemberInfo, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
				showToast("修改失败");
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				showToast("修改完成");
			}
		});
	}

}
